from pathlib import Path
from qfluentwidgets import InfoBar, StateToolTip

from view.base import ReturnView, TableFrameBase
from components import OpenFileDialog
from common import TxtToPdfThread


class TxtToPdfView(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.tableFrame = TableFrameBase()
        self.tableFrame.setTitle('Txt 转 Pdf')
        self.tableFrame.setHeaders(['文件名称', '完整路径', '文件类型'])
        self.vBox.addWidget(self.tableFrame)

        self.stateToolTip = StateToolTip('PDF To Word', 'PDF正在转换Word，请稍后...', self)
        self.stateToolTip.hide()

        self.to_pdf_thread = TxtToPdfThread(self)

        self.tableFrame.added.connect(self.added_event)
        self.tableFrame.saved.connect(self.saved_event)
        self.tableFrame.started.connect(self.started_event)

        self.to_pdf_thread.started.connect(self.started_thread)
        self.to_pdf_thread.error.connect(self.error_thread)
        self.to_pdf_thread.finished.connect(self.finished_thread)

    def added_event(self):
        files = OpenFileDialog(self).getOpenFileNames(filter='文本文件(*.txt);')[0]
        for file in files:
            if file in self.tableFrame.getColumnValues(1):
                continue
            self.tableFrame.addItem([Path(file).name, file, Path(file).suffix])

    def saved_event(self):
        file = OpenFileDialog(self).getExistingDirectory()
        self.tableFrame.setLineText(file)

    def started_event(self):
        files = self.tableFrame.getColumnValues(1)
        save_path = self.tableFrame.lineText()
        if len(files) == 0:
            return
        if save_path is False:
            return
        self.to_pdf_thread.set_value(files, save_path)
        self.to_pdf_thread.start()

    def started_thread(self):
        self.stateToolTip.show()

    def error_thread(self, msg):
        InfoBar.warning('错误', msg, duration=5000, parent=self)

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('提示', '转换完毕', duration=3000, parent=self)

    def resizeEvent(self, event):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)
